<?php

require_once('entities/ShopCategory.php');

class ShopCategoryModel
{
	public $category;

	public function __construct() {
		$this->category = new ShopCategory();
	}

	public function create($data) {
		global $entityManager;
		$messageUpload = Helper::uploadFile('image', 'image/jpeg|image/png|image/gif');
		if ($messageUpload['type'] == 'error') {
			Helper::setMessage($messageUpload);
			return false;
		} else {
			$data['image'] = $messageUpload['message'];
		}
		$data['alias'] = Helper::stringURLSafe($data['title']);

		$this->category->setParentId($data['parent_id']);
		$this->category->setTitle($data['title']);
		$this->category->setAlias($data['alias']);
		$this->category->setDescription($data['description']);
		$this->category->setStatus($data['status']);
		$this->category->setImage($data['image']);

		$entityManager->persist($this->category);
		$entityManager->flush();

		return true;
	}

	public function delete($data) {
	}

	public function edit($data) {

	}

	public function getList() {
		global $entityManager;
		$cateRes = $entityManager->getRepository('ShopCategory');
    $result = $cateRes->findAll();
		return $result;
	}

	public function optionCategory($root, $string = '', &$result) {
		global $entityManager;
		$cateList = $entityManager->getRepository('ShopCategory')->findBy(array('parent_id' => $root));
		foreach ($cateList as $cate) {
			if ($cate->getId() == 1) {
				$result .= '<option value="'. $cate->getId() .'">Root</option>';
			} else {
				$result .= '<option value="'. $cate->getId() .'">' . $string . $cate->getTitle() . '</option>';
			}
			$this->optionCategory($cate->getId(), $string . '--', $result);
		}
	}

	public function test() {
		return 'This is a test';
	}
}